package com.eda;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.Spinner;

import com.eda.common.DataBean;
import com.eda.common.MyListView;
import com.eda.common.MyListView.OnRefreshListener;
import com.eda.db.DatabaseHelper;

public class OwnerFindActivity extends Activity {
	/* 定义页面元素 */
	EditText start;
	EditText end;
	EditText type;
	EditText length;
	EditText loadDate;

	Button datePicker;
	Button search;
	Button commonFunction;

	final static int TRUCK = 1;
	final static int LOCATION = 2;
	final static int DATEPICKER = 3;

	EditText tempLocation;
	DatabaseHelper mOpenHelper;
	Spinner spprovince;
	Spinner spcity;
	Spinner sparea;
	SQLiteDatabase db;
	
	LayoutInflater inflater;
	List<Map<String, String>> list;
	String userId;
	SharedPreferences loginInfo;
	DataBean bean ;
	TextView text;
	int total;
	LinearLayout listLayout;
	SimpleAdapter adapter;
	MyListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_owner_find_tab);

		commonFunction = (Button) OwnerFindActivity.this.getParent()
				.findViewById(R.id.commonFunction);
		commonFunction.setVisibility(-1);
		commonFunction.setOnClickListener(goSearchListener);
		loginInfo = getSharedPreferences("LOGGING_INFO", 0);
		bean = new DataBean();

		mOpenHelper = new DatabaseHelper(this);
		db = mOpenHelper.getWritableDatabase();

		// 元素实例化
		start = (EditText) findViewById(R.id.ownerFindStart);
		end = (EditText) findViewById(R.id.ownerFindEnd);
		type = (EditText) findViewById(R.id.ownerFindTruckType);
		length = (EditText) findViewById(R.id.ownerFindTruckLenght);
		loadDate = (EditText) findViewById(R.id.ownerFindLoadDate);
		datePicker = (Button) findViewById(R.id.ownerFindDatePicker);
		search = (Button) findViewById(R.id.ownerFindSearch);

		// 添加监听
		start.setFocusable(false);
		start.setClickable(true);
		start.setInputType(InputType.TYPE_NULL);
		start.setOnClickListener(locationListener);

		end.setFocusable(false);
		end.setClickable(true);
		end.setInputType(0);
		end.setOnClickListener(locationListener);

		type.setFocusable(false);
		type.setClickable(true);
		type.setInputType(0);
		type.setOnClickListener(typeListener);

		datePicker.setOnClickListener(datePickerListener);
		search.setOnClickListener(searchListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.owner_find, menu);
		return true;
	}

	// 地点选择
	OnClickListener locationListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			tempLocation = (EditText) arg0;
			showDialog(LOCATION);
		}
	};

	// 时间选择
	OnClickListener datePickerListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			showDialog(DATEPICKER);
		}
	};

	// 车型选择
	OnClickListener typeListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			tempLocation = (EditText) arg0;
			showDialog(TRUCK);
		}
	};

	// 查找监听
	OnClickListener searchListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			commonFunction.setVisibility(0);
			commonFunction.setText("搜索");
			searchDataList(0,10,1);
		}
	};

	// 弹出框控制
	/* 地点选择框，车辆选择框 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LOCATION:
			return buildProviceDialog(OwnerFindActivity.this);
		case TRUCK:
			return buildTypeDialog(OwnerFindActivity.this);
		case DATEPICKER:
			return buildDateDialog(OwnerFindActivity.this);
		default:
			return null;

		}
	}

	// 地区选择弹出框
	private Dialog buildProviceDialog(Context context) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View provinceView = inflater.inflate(R.layout.location_layout,
				null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(provinceView);
		builder.setTitle(R.string.alert_dialog_text_entry);

		spprovince = (Spinner) provinceView.findViewById(R.id.spprovince);
		spcity = (Spinner) provinceView.findViewById(R.id.spcity);
		sparea = (Spinner) provinceView.findViewById(R.id.sparea);

		String[] col = { "cityName" };
		Cursor cur = db.query("province", col, "parentid=0", null, null, null,
				null);

		List<String> provinceList = new ArrayList<String>();
		while (cur.moveToNext()) {
			provinceList.add(cur.getString(0));
		}
		ArrayAdapter provinceAdapter = new ArrayAdapter(OwnerFindActivity.this,
				android.R.layout.simple_spinner_item, provinceList);
		provinceAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
		spprovince.setAdapter(provinceAdapter);
		spprovince.setOnItemSelectedListener(provinceSelectedListener);

		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});

		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						tempLocation.setText("");
					}
				});

		return builder.create();
	}

	// 选择省事件
	private OnItemSelectedListener provinceSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			try {
				Spinner spProvince = (Spinner) parent;
				String selectedProvince = (String) spProvince
						.getItemAtPosition(position);
				ArrayAdapter cityAdapter = null;

				String[] col = { "codeid", "cityName" };
				Cursor cur = db.query("province", col, "cityName='"
						+ selectedProvince + "'", null, null, null, null);
				int pid = -1;
				if (cur.moveToNext()) {
					pid = cur.getInt(0);// 得到省份的id
				}

				cur = db.query("province", col, "parentid=" + pid, null, null,
						null, null);

				List<String> cityList = new ArrayList<String>();
				while (cur.moveToNext()) {
					cityList.add(cur.getString(1));
				}
				cityAdapter = new ArrayAdapter(OwnerFindActivity.this,
						android.R.layout.simple_spinner_item, cityList);
				cityAdapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spcity.setAdapter(cityAdapter);
				spcity.setOnItemSelectedListener(citySelectedListener);
			} catch (Exception e) {
				Log.d("WineStock", "Select Province error:" + e.getMessage());
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 选择市事件
	private OnItemSelectedListener citySelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			try {
				Spinner spCity = (Spinner) parent;
				String selectedCity = (String) spCity
						.getItemAtPosition(position);
				ArrayAdapter areaAdapter = null;

				String[] col = { "codeid", "cityName" };
				Cursor cur = db.query("province", col, "cityName='"
						+ selectedCity + "'", null, null, null, null);
				int pid = -1;
				if (cur.moveToNext()) {
					pid = cur.getInt(0);// 得到省份的id
				}

				cur = db.query("province", col, "parentid=" + pid, null, null,
						null, null);

				List<String> areaList = new ArrayList<String>();
				while (cur.moveToNext()) {
					areaList.add(cur.getString(1));
				}
				areaAdapter = new ArrayAdapter(OwnerFindActivity.this,
						android.R.layout.simple_spinner_item, areaList);
				areaAdapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				sparea.setAdapter(areaAdapter);
				sparea.setOnItemSelectedListener(areaSelectedListener);
			} catch (Exception e) {
				Log.d("WineStock", "Select Province error:" + e.getMessage());
			}
		}

		private OnItemSelectedListener citySelectedListener = new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					Spinner spCity = (Spinner) parent;
					String selectedCity = (String) spCity
							.getItemAtPosition(position);
					ArrayAdapter areaAdapter = null;

					String[] col = { "codeid", "cityName" };
					Cursor cur = db.query("province", col,
							"cityName='selectedProvince'", null, null, null,
							null);
					int pid = -1;
					if (cur.moveToNext()) {
						pid = cur.getInt(0);// 得到省份的id
					}

					cur = db.query("province", col, "parentid=" + pid, null,
							null, null, null);

					List<String> areaList = new ArrayList<String>();
					if (cur.moveToNext()) {
						areaList.add(cur.getString(1));
					}
					areaAdapter = new ArrayAdapter(OwnerFindActivity.this,
							android.R.layout.simple_spinner_item, areaList);
					areaAdapter
							.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					sparea.setAdapter(areaAdapter);
					sparea.setOnItemSelectedListener(areaSelectedListener);
				} catch (Exception e) {
					Log.d("WineStock",
							"Select Province error:" + e.getMessage());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}
		};

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 选择区事件
	private OnItemSelectedListener areaSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {

			Spinner spArea = (Spinner) parent;
			String selectedCity = (String) spArea.getItemAtPosition(position);
			tempLocation.setText(selectedCity);
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 车型选择弹出框
	private Dialog buildTypeDialog(Context context) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View provinceView = inflater.inflate(R.layout.location_layout,
				null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(provinceView);
		builder.setTitle(R.string.alert_dialog_text_entry);

		spprovince = (Spinner) provinceView.findViewById(R.id.spprovince);

		String[] col = { "name" };
		db = mOpenHelper.getWritableDatabase();
		Cursor cur = db.query("truck", col, null, null, null, null, null);

		List<String> provinceList = new ArrayList<String>();
		while (cur.moveToNext()) {
			provinceList.add(cur.getString(0));
		}
		ArrayAdapter provinceAdapter = new ArrayAdapter(OwnerFindActivity.this,
				android.R.layout.simple_spinner_item, provinceList);
		provinceAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式
		spprovince.setAdapter(provinceAdapter);
		spprovince.setOnItemSelectedListener(typeSelectedListener);

		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});

		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						tempLocation.setText("");
					}
				});

		return builder.create();
	}

	// 车辆选择事件
	private OnItemSelectedListener typeSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {

			Spinner spType = (Spinner) parent;
			String type = (String) spType.getItemAtPosition(position);
			tempLocation.setText(type);
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
		}
	};

	// 日期选择弹出框
	private Dialog buildDateDialog(Context context) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View datePickerView = inflater.inflate(
				R.layout.activity_date_pick, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(datePickerView);
		builder.setTitle(R.string.alert_dialog_text_entry);

		DatePicker dp = (DatePicker) datePickerView
				.findViewById(R.id.date_picker);
		dp.init(2000, 1, 1, dateChangeListener);

		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});

		builder.setNegativeButton(R.string.alert_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						loadDate.setText("");
					}
				});

		return builder.create();
	}

	OnDateChangedListener dateChangeListener = new OnDateChangedListener() {

		@Override
		public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) {
			loadDate.setText(arg1 + "年" + (arg2 + 1) + "月" + arg3 + "日");

		}
	};

	OnClickListener goSearchListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			setContentView(R.layout.activity_pub_find_tab);

			commonFunction = (Button) OwnerFindActivity.this.getParent()
					.findViewById(R.id.commonFunction);
			commonFunction.setVisibility(-1);

			length = (EditText) findViewById(R.id.pubFindLength);
			loadDate = (EditText) findViewById(R.id.pubFindLoadDate);

			start = (EditText) findViewById(R.id.pubFindStart);
			start.setFocusable(false);
			start.setClickable(true);
			start.setInputType(InputType.TYPE_NULL);
			start.setOnClickListener(locationListener);

			end = (EditText) findViewById(R.id.pubFindEnd);
			end.setFocusable(false);
			end.setClickable(true);
			end.setInputType(InputType.TYPE_NULL);
			end.setOnClickListener(locationListener);

			type = (EditText) findViewById(R.id.pubFindType);
			type.setFocusable(false);
			type.setClickable(true);
			type.setInputType(InputType.TYPE_NULL);
			type.setOnClickListener(locationListener);

			datePicker = (Button) findViewById(R.id.pubFindDatePicker);
			datePicker.setOnClickListener(datePickerListener);

			search = (Button) findViewById(R.id.pubFindSearch);
			search.setOnClickListener(searchListener);

		}
	};
	
	private void searchDataList(int from, int to,int type) {
		List<Map<String, String>> allresult = generateDataList(from,to);
		total = Integer.parseInt(allresult.get(allresult.size()-1).get("total"));
		setContent(total,allresult,type);
	}
	
	private void setContent(int total,List<Map<String, String>> allresult,int type){
		allresult.remove(allresult.size()-1);
		List<Map<String, String>> tempList =  allresult;
		if(type==1){
			list = tempList;
		}else{
			for(int i=0;i<tempList.size()-1;i++){
				list.add(i,tempList.get(tempList.size()-1-i));
			}
		}
		
		if(type==1){
			adapter = new SimpleAdapter(this, list, R.layout.listview_content,
					new String[] { "title", "info1", "info2"}, new int[] {
							R.id.title, R.id.info1, R.id.info2});
			listView = new MyListView(this);
			listView.setAdapter(adapter);

			listView.setonRefreshListener(refresh);

			inflater = LayoutInflater.from(this);
			listLayout = (LinearLayout) inflater.inflate(
					R.layout.truck_list, null);
			text = (TextView)listLayout.findViewById(R.id.listtotal);
			text.setText("共找到"+total+"条匹配货源");
			listLayout.addView(listView);
			setContentView(listLayout);
		}
	}

	OnRefreshListener refresh = new OnRefreshListener() {

		@Override
		public void onRefresh() {
			new AsyncTask<Void, Void, Void>() {
				protected Void doInBackground(Void... params) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(total>=list.size()){
						searchDataList(list.size(),list.size()+10,2);
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					adapter.notifyDataSetChanged();
					listView.onRefreshComplete();
				}

			}.execute(null);
		}
	};
	
	private List<Map<String, String>> generateDataList(int from ,int to) {
		userId = loginInfo.getString("USER_NAME", "");
		Map<String,String> params = new HashMap<String,String>();
		params.put("userId", userId);
		params.put("from", String.valueOf(from));
		params.put("to", String.valueOf(to));
		
		params.put("start", start.getText().toString());
		params.put("end", end.getText().toString());
		params.put("type", type.getText().toString());
		params.put("length", length.getText().toString());
		params.put("startDate", loadDate.getText().toString());
		
		return bean.getCargo(params);
	}
}
